import { createRouter, createWebHashHistory, Router, RouteRecordRaw } from 'vue-router'
import { store } from '../store'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/index',
  },
  {
    path: '/login',
    name: 'Login',
    component: ()=>import('../views/Login.vue'),
  },
  {
    path: '/index',
    name: 'Index',
    component: ()=>import('../components/Index.vue'),
    children:[
      {path:'/menuTree',name:'menuTree',component:()=>import('../views/Menu.vue')},
      {path:'/user',name:'user',component:()=>import('../views/User.vue')},
      {path:'/role',name:'role',component:()=>import('../views/Role.vue')},
      {path:'/article',name:'article',component:()=>import('../views/article.vue')},
      {path:'/tag',name:'tag',component:()=>import('../views/tag.vue')},
      {path:'/topic',name:'topic',component:()=>import('../views/topic.vue')},
      {path:'/notice',name:'notice',component:()=>import('../views/notice.vue')},
    ]
  },


]

const router: Router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to,from,next)=>{
  if(localStorage.getItem('token') && to.name!=='Login'){
    store.dispatch('userModule/getMenuTree')
  }
  switch(to.name){
    case 'Login':
      next();
      break;
    default:
      if(localStorage.getItem('token')){
        next()
      }else{
        next({path:'/login'})
      }
      break;
  }
})

export default router
